package org.layui.servlet;


import org.layui.utils.FileUploadUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * 文件上传 -- 实现富文件框中的上传图片
 */
@WebServlet("/api/file/upload")
@MultipartConfig
public class FileUploadServlet extends BaseServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part part = req.getPart("attach") ;

        // 使用上传工具类来实现文件的上传
        FileUploadUtil fuu = new FileUploadUtil() ;
        String path = req.getServletContext().getRealPath("/file/editor") ;

        File f = new File(path) ;
        if(!f.exists()) {
            f.mkdir();
        }

        // 设置允许上传文件的大小和类型
        fuu.setMaxSize(10*1024*1024);
        fuu.setAllowFileExt("jpg,png,jpeg");

        // 文件上传，并返回上传的文件名
        String filename = fuu.upload(part, path,true) ;

        print(resp, successJson(filename,200,"上传文件成功"));
    }
}
